﻿using Microsoft.Rtc.Collaboration;
using Microsoft.Rtc.Collaboration.Presence;
using Microsoft.Rtc.Signaling;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace MSFT_SAMPLE_ConferencingServiceLibrary
{
    public class UCMAUtil
    {
        
        private ServerPlatformSettings _platformSettings;

        private CollaborationPlatform _platform;

        private string _applicationUserAgent;

        private string _applicationHostFQDN;

        private int _applicationHostPort;

        private string _computerGRUU;

        private string _certificateFriendlyName;

        private X509Certificate2 _certificate;

        private string _registrarFQDN;

        private const string _sipPrefix = "sip:";

        private static ManualResetEvent _appFinished;

        private static CollaborationPlatform _serverCollabPlatform;

        static UCMAUtil()
        {
            UCMAUtil._appFinished = new ManualResetEvent(false);
        }
        public UCMAUtil()
        {
            _applicationUserAgent = Properties.Settings.Default.UserAgent;
            _applicationHostFQDN = Properties.Settings.Default.AppHostFQDN;
            _applicationHostPort = Properties.Settings.Default.Port; 
            _certificateFriendlyName = Properties.Settings.Default.CerftificateName;
            _computerGRUU = Properties.Settings.Default.GRUU;
            _registrarFQDN = Properties.Settings.Default.RegistrarFQDN;
        }
        public void CreateAndStartServerPlatform()
        {
            _certificate = GetLocalCertificate(_certificateFriendlyName);
            _platformSettings = new ServerPlatformSettings(_applicationUserAgent,
                    _applicationHostFQDN,
                    _applicationHostPort,
                    _computerGRUU,
                    _certificate);
            _platform = new CollaborationPlatform(_platformSettings);
            UCMAUtil._serverCollabPlatform = _platform;
            IAsyncResult asyncResult = UCMAUtil._serverCollabPlatform.BeginStartup(null, _serverCollabPlatform);
            UCMAUtil._serverCollabPlatform.EndStartup(asyncResult);
        }

        
        public UserEndpoint CreateUserEndpoint(string userUri)
        {
            return new UserEndpoint(UCMAUtil._serverCollabPlatform, new UserEndpointSettings(userUri, this._registrarFQDN)); 
        }

        public bool DoSelfSub(UserEndpoint userEndpoint)
        {
            IAsyncResult asyncResult = userEndpoint.LocalOwnerPresence.BeginSubscribe(null, null);
            userEndpoint.LocalOwnerPresence.EndSubscribe(asyncResult);
            Thread.Sleep(2000);
            return true;
        }

        public bool EstablishUserEndpoint(UserEndpoint userEndpoint)
        {
            List<SignalingHeader> signalingHeaders = new List<SignalingHeader>()
			{
				SignalingHeader.MicrosoftSupportedForking,
				SignalingHeader.MicrosoftSupportedPresence,
				SignalingHeader.MicrosoftSupportedEventCategories
			};
            IAsyncResult asyncResult = userEndpoint.BeginEstablish(signalingHeaders, null, null);
            userEndpoint.EndEstablish(asyncResult);
            
            return true;
        }

        public static X509Certificate2 GetLocalCertificate(string friendlyName)
        {
            X509Store x509Store = new X509Store(StoreLocation.LocalMachine);
            x509Store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificates = x509Store.Certificates;
            x509Store.Close();
            X509Certificate2Enumerator enumerator = certificates.GetEnumerator();
            while (enumerator.MoveNext())
            {
                X509Certificate2 current = enumerator.Current;
                if (!current.FriendlyName.Equals(friendlyName, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                return current;
            }
            return null;
        }

        public bool isRunning()
        {
            if (_serverCollabPlatform != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        internal void ShutdownPlatform()
        {
            if (UCMAUtil._serverCollabPlatform != null)
            {
                IAsyncResult asyncResult = UCMAUtil._serverCollabPlatform.BeginShutdown(null, null);
                UCMAUtil._serverCollabPlatform.EndShutdown(asyncResult);
            }
        }
    }
}
